import 'dart:convert';
import 'package:flutter/material.dart';
import '../const.dart';
//添加第三方网络请求依赖
import 'package:http/http.dart' as http;

import 'chat_data.dart';

class ChatPage extends StatefulWidget {
  @override
  _ChatPageState createState() => _ChatPageState();
}


Widget _buildItem(String img,String title){
  return PopupMenuItem<String>(
    value: title,
    child: Row(
      children: <Widget>[
        Image(image: AssetImage(img),width: 22,),
        Container(width: 10,),
        Text(title,style: TextStyle(color: Colors.white),)
      ],
    )
  );
}
List<PopupMenuItem<String>> _buildPopupMenuItem(BuildContext context){
  return <PopupMenuItem<String>>[
    _buildItem("images/发起群聊.png", "发起群聊"),
    _buildItem("images/添加朋友.png", "添加朋友"),
    _buildItem("images/扫一扫1.png", "扫一扫"),
    _buildItem("images/收付款.png", "收付款")
  ];
}

class _ChatPageState extends State<ChatPage> {
  List<ChatData> _datas = [];
  bool _cancelConnect = false;//设置标识位，防止多次请求
  @override
  void initState(){
    super.initState();
    getDatas().then((List<ChatData> datas){
      if(!_cancelConnect){
        setState(() {
          _datas = datas;
        });
      }
    }).catchError((e){
      print(e);
    }).whenComplete((){
      print('完毕');
    }).timeout(Duration(seconds: 6)).catchError((timeout){
      _cancelConnect = true;
      print('超时：${timeout}');
    });
  }
  //网络请求
  Future<List<ChatData>> getDatas() async{
    _cancelConnect = false;
    final String url = 'http://rap2api.taobao.org/app/mock/224518/api/chat/list';
    final response = await http.get(url);
    if(response.statusCode == 200){
      final responseBody = json.decode(response.body);
      List<ChatData> chatList = responseBody['chat_list'].map<ChatData>((item)=>ChatData.formJson(item)).toList();
      return chatList;
    }else{
      throw Exception('statusCode:${response.statusCode}');
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,//修改状态栏
        backgroundColor: ThemeColor,
        title: Text("微信",style: TextStyle(color: Colors.black),),
        centerTitle: true,//针对安卓标题的
        actions: <Widget>[
          Container(
            margin: EdgeInsets.only(right: 10),
            child: PopupMenuButton(
              offset: Offset(0, 60.0),
              child: Image(image: AssetImage("images/圆加.png"),width: 26,),
              itemBuilder: _buildPopupMenuItem
            ),
          )
        ],
      ),
      body: Center(
        child: _datas.length==0?Center(child: Text("Loading.."),):
        ListView.builder(
          itemCount: _datas.length,
          itemBuilder: (BuildContext context,int index){
            return ListTile(
              title: Text(_datas[index].name),
              subtitle: Container(
                height: 20,
                width: 20,
                child: Text(
                  _datas[index].message,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              leading: CircleAvatar(
                backgroundImage: NetworkImage(_datas[index].imageUrl),
              ),
            );
          },
        ),
      ),
    );
  }
}
